package cn.com.mayue.guava.concurrency;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.*;
import org.junit.Test;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import com.google.common.util.concurrent.AsyncFunction;

/**
 * Created by Administrator on 2016/12/22.
 * 多表插入数据时，可以考虑使用并发插入数据
 * 可以监听的Future
 */
public class ListenableFutureTest {
    @Test
    public void test() throws Exception {
        //init ListeningExecutorService
        ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
        //使用submit方法初始化 ListenableFuture
        List<ListenableFuture<?>> listenableFutures = Lists.newArrayList();
        listenableFutures.add(executorService.submit(new Callable<Integer>() {
            public Integer call() throws Exception {
                TimeUnit.SECONDS.sleep(3);
                System.out.println("exec 1..");

//                throw new Exception();
                return 1;
            }
        }));

        listenableFutures.add(executorService.submit(new Callable<Integer>() {
            public Integer call() {
                System.out.println("exec 2..");
                return 2;
            }
        }));

        ListenableFuture<List<Object>> results = Futures.allAsList(listenableFutures);
        String result = null;
        for (Object obj : results.get()) {
            if (obj != null) {
                System.out.println(obj.toString());
                result = obj.toString();
            }
        }
        System.out.println(result);
    }
}
